package bookmanagementsystem.gui;

import bookmanagementsystem.dao.UserDAO;
import bookmanagementsystem.model.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginFrame extends JFrame {

    public LoginFrame() {
        setTitle("图书管理系统 - 登录");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initUI();
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));

        JTextField userIDField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        panel.add(new JLabel("用户ID："));
        panel.add(userIDField);
        panel.add(new JLabel("密码："));
        panel.add(passwordField);
        panel.add(loginButton);
        panel.add(registerButton);

        getContentPane().add(panel);

        // 登录按钮点击事件处理
        loginButton.addActionListener(new LoginButtonActionListener(userIDField, passwordField));

        // 注册按钮点击事件处理
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RegistrationFrame registrationFrame = new RegistrationFrame();
                registrationFrame.setVisible(true);
            }
        });

        setVisible(true);
    }

    private  class LoginButtonActionListener implements ActionListener {
        private JTextField userIDField;
        private JPasswordField passwordField;

        public LoginButtonActionListener(JTextField userIDField, JPasswordField passwordField) {
            this.userIDField = userIDField;
            this.passwordField = passwordField;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            UserDAO userDAO = new UserDAO();
            User loggedInUser = userDAO.loginUser(userIDField.getText(), new String(passwordField.getPassword()));
            if (loggedInUser!= null) {
                JOptionPane.showMessageDialog(null, "登录成功！");
                MainFrame mainFrame = new MainFrame(loggedInUser.getUserID());
                mainFrame.setVisible(true);
               dispose();
            } else {
                JOptionPane.showMessageDialog(null, "登录失败，请检查用户ID和密码。");
            }
        }
    }

    public static void main(String[] args) {

                LoginFrame loginFrame = new LoginFrame();
            }


}